Documentation

The Java™ Tutorials
Hide TOC
How to Use Color Choosers如何使用颜色选择器
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Color Choosers如何使用颜色选择器

Use the JColorChooser class to enable users to choose from a palette of colors. 使用JColorChooser类,用户可以从调色板中选择颜色。A color chooser is a component that you can place anywhere within your program GUI. 颜色选择器是一个可以放置在程序GUI中任何位置的组件。The JColorChooser API also makes it easy to bring up a dialog (modal or not) that contains a color chooser.JColorChooser API还可以轻松地打开包含颜色选择器的对话框(模式或非模式)。

Here is a picture of an application that uses a color chooser to set the text color in a banner:下面是一个应用程序的图片,该应用程序使用颜色选择器设置横幅中的文本颜色:

A snapshot of ColorChooserDemo, which contains a standard color chooser.

Try this: 

The source code for the program is in ColorChooserDemo.java.该程序的源代码位于ColorChooserDemo.java中。

The color chooser consists of everything within the box labeled Choose Text Color. 颜色选择器由标记为“选择文本颜色”的框中的所有内容组成。This is what a standard color chooser looks like in the Java Look & Feel. 这就是Java外观中标准颜色选择器的外观。It contains two parts, a tabbed pane and a preview panel. 它包含两个部分,一个选项卡式窗格和一个预览面板。The three tabs in the tabbed pane select chooser panels. 选项卡窗格中的三个选项卡选择选择器面板The preview panel below the tabbed pane displays the currently selected color.选项卡窗格下方的预览面板显示当前选定的颜色。

Here is the code from the example that creates a JColorChooser instance and adds it to a container:下面是创建JColorChooser实例并将其添加到容器的示例代码:

public class ColorChooserDemo extends JPanel ... {
    public ColorChooserDemo() {
        super(new BorderLayout());
        banner = new JLabel("Welcome to the Tutorial Zone!",
                            JLabel.CENTER);
        banner.setForeground(Color.yellow);
        . . .
        tcc = new JColorChooser(banner.getForeground());
        . . .
        add(tcc, BorderLayout.PAGE_END);
    }

The JColorChooser constructor in the previous code snippet takes a Color argument, which specifies the chooser's initially selected color. 上一个代码片段中的JColorChooser构造函数采用一个颜色参数,该参数指定选择器最初选择的颜色。If you do not specify the initial color, then the color chooser displays Color.white. 如果未指定初始颜色,则颜色选择器将显示Color.whiteSee the Color API documentation for a list of color constants you can use.有关可以使用的颜色常数列表,请参阅ColorAPI文档

A color chooser uses an instance of ColorSelectionModel to contain and manage the current selection. 颜色选择器使用ColorSelectionModel的实例来包含和管理当前选择。The color selection model fires a change event whenever the user changes the color in the color chooser. 每当用户在颜色选择器中更改颜色时,颜色选择模型将触发更改事件。The example program registers a change listener with the color selection model so that it can update the banner at the top of the window. 示例程序向颜色选择模型注册一个更改侦听器,以便它可以更新窗口顶部的横幅。The following code registers and implements the change listener:以下代码注册并实现更改侦听器:

tcc.getSelectionModel().addChangeListener(this);
. . .
public void stateChanged(ChangeEvent e) {
    Color newColor = tcc.getColor();
    banner.setForeground(newColor);
}

See How to Write a Change Listener for general information about change listeners and change events.有关更改侦听器和更改事件的一般信息,请参阅如何编写更改侦听器

A basic color chooser, like the one used in the example program, is sufficient for many programs. 一个基本的颜色选择器,如示例程序中使用的,对于许多程序来说都是足够的。However, the color chooser API allows you to customize a color chooser by providing it with a preview panel of your own design, by adding your own chooser panels to it, or by removing existing chooser panels from the color chooser. 但是,颜色选择器API允许您通过为颜色选择器提供自己设计的预览面板、向其添加自己的选择器面板或从颜色选择器中删除现有选择器面板来自定义颜色选择器。Additionally, the JColorChooser class provides two methods that make it easy to use a color chooser within a dialog.此外,JColorChooser类提供了两种方法,可以轻松地在对话框中使用颜色选择器。

The rest of this section discusses these topics:本节其余部分将讨论以下主题:

Another Example: 另一个例子:ColorChooserDemo2

Now let's turn our attention to ColorChooserDemo2, a modified version of the previous demo program that uses more of the JColorChooser API. 现在让我们将注意力转向ColorChooserDemo2,它是先前演示程序的修改版本,使用了更多的JColorChooser API。


Try this: 

Here is a picture of ColorChooserDemo2:以下是ColorChooserDemo2的图片:

A snapshot of ColorChooserDemo, which contains a custom color chooser.

This program customizes the banner text color chooser in these ways:此程序通过以下方式自定义横幅文本颜色选择器:

Removing or Replacing the Preview Panel删除或替换预览面板 covers the first customization. 涵盖第一个定制。Creating a Custom Chooser Panel创建自定义选择器面板 discusses the last two.讨论后两者。

This program also adds a button that brings up a color chooser in a dialog, which you can use to set the banner background color.该程序还添加了一个按钮,用于在对话框中打开颜色选择器,您可以使用该按钮设置横幅背景颜色。

Showing a Color Chooser in a Dialog在对话框中显示颜色选择器

The JColorChooser class provides two class methods to make it easy to use a color chooser in a dialog. JColorChooser类提供了两个类方法,以便于在对话框中使用颜色选择器。ColorChooserDemo2 uses one of these methods, showDialog, to display the background color chooser when the user clicks the Show Color Chooser... button. ColorChooserDemo2使用其中一种方法showDialog,在用户单击“显示颜色选择器…”按钮时显示背景颜色选择器。Here is the single line of code from the example that brings up the background color chooser in a dialog:下面是示例中的一行代码,在对话框中显示背景颜色选择器:

Color newColor = JColorChooser.showDialog(
                     ColorChooserDemo2.this,
                     "Choose Background Color",
                     banner.getBackground());

The first argument is the parent for the dialog, the second is the dialog title, and the third is the initially selected color.第一个参数是对话框的父参数,第二个是对话框标题,第三个是最初选择的颜色。

The dialog disappears under three conditions: the user chooses a color and clicks the OK button, the user cancels the operation with the Cancel button, or the user dismisses the dialog with a frame control. 对话框在三种情况下消失:用户选择颜色并单击“确定”按钮,用户使用“取消”按钮取消操作,或用户使用框架控件取消对话框。If the user chooses a color, the showDialog method returns the new color. 如果用户选择颜色,showDialog方法将返回新颜色。If the user cancels the operation or dismisses the window, the method returns null. 如果用户取消操作或关闭窗口,该方法将返回nullHere is the code from the example that updates the banner background color according to the value returned by showDialog:下面是根据showDialog返回的值更新横幅背景颜色的示例代码:

if (newColor != null) {
    banner.setBackground(newColor);
}

The dialog created by showDialog is modal. showDialog创建的对话框是模态对话框。If you want a non-modal dialog, you can use JColorChooser's createDialog method to create the dialog. 如果需要非模态对话框,可以使用JColorChoosercreateDialog方法来创建对话框。This method also lets you specify action listeners for the OK and Cancel buttons in the dialog window. 此方法还允许您为对话框窗口中的“确定”和“取消”按钮指定操作侦听器。Use JDialog's show method to display the dialog created by this method. 使用JDialogshow方法显示由该方法创建的对话框。For an example that uses this method, see Specifying Other Editors in the How to Use Tables section.有关使用此方法的示例,请参阅“如何使用表格”部分中的“指定其他编辑器”。

Removing or Replacing the Preview Panel删除或替换预览面板

By default, the color chooser displays a preview panel. 默认情况下,颜色选择器显示预览面板。ColorChooserDemo2 removes the text color chooser's preview panel with this line of code:ColorChooserDemo2使用以下代码行删除文本颜色选择器的预览面板:

tcc.setPreviewPanel(new JPanel());

This effectively removes the preview panel because a plain JPanel has no size and no default view. 这有效地删除了预览面板,因为普通JPanel没有大小,也没有默认视图。To set the preview panel back to the default, use null as the argument to setPreviewPanel.要将预览面板设置回默认值,请使用null作为setPreviewPanel的参数。

To provide a custom preview panel, you also use setPreviewPanel. 要提供自定义预览面板,还可以使用setPreviewPanelThe component you pass into the method should inherit from JComponent, specify a reasonable size, and provide a customized view of the current color. 传递到方法中的组件应该继承JComponent,指定合理的大小,并提供当前颜色的自定义视图。To get notified when the user changes the color in the color chooser, the preview panel must register as a change listener on the color chooser's color selection model as described previously.要在用户更改颜色选择器中的颜色时获得通知,预览面板必须注册为颜色选择器的颜色选择模型上的更改侦听器,如前所述

Creating a Custom Chooser Panel创建自定义选择器面板

The default color chooser provides five chooser panels:默认颜色选择器提供五个选择器面板:

You can extend the default color chooser by adding chooser panels of your own design with addChooserPanel, or you can limit it by removing chooser panels with removeChooserPanel.可以通过使用addChooserPanel添加自己设计的选择器面板来扩展默认颜色选择器,也可以通过使用removeChooserPanel删除选择器面板来限制默认颜色选择器。

If you want to remove all of the default chooser panels and add one or more of your own, you can do this with a single call to setChooserPanels. 如果要删除所有默认选择器面板并添加一个或多个自己的面板,可以通过调用setChooserPanels来完成此操作。ColorChooserDemo2 uses this method to replace the default chooser panels with an instance of CrayonPanel, a custom chooser panel. 使用此方法将默认选择器面板替换为自定义选择器面板CrayonPanel的实例。Here is the call to setChooserPanels from that example:下面是该示例中对setChooserPanels的调用:

//Override the chooser panels with our own.
AbstractColorChooserPanel panels[] = { new CrayonPanel() };
tcc.setChooserPanels(panels);

The code is straightforward: it creates an array containing the CrayonPanel. 代码很简单:它创建了一个包含CrayonPanel的数组。Next the code calls setChooserPanels to set the contents of the array as the color chooser's chooser panels.接下来,代码调用setChooserPanels,将数组的内容设置为颜色选择器的选择器面板。

CrayonPanel is a subclass of AbstractColorChooserPanel and overrides the five abstract methods defined in its superclass:AbstractColorChooserPanel的子类,并重写其超类中定义的五个抽象方法:

void buildChooser()
Creates the GUI that comprises the chooser panel. 创建包含选择器面板的GUI。The example creates four toggle buttons — one for each crayon — and adds them to the chooser panel.该示例创建了四个切换按钮—每个蜡笔一个—并将其添加到选择器面板。
void updateChooser()
This method is called whenever the chooser panel is displayed. 每当显示选择器面板时,都会调用此方法。The implementation of this method selects the toggle button that represents the currently selected color. 此方法的实现将选择表示当前选定颜色的切换按钮。
public void updateChooser() {
    Color color = getColorFromModel();
    if (Color.red.equals(color)) {
        redCrayon.setSelected(true);
    } else if (Color.yellow.equals(color)) {
        yellowCrayon.setSelected(true);
    } else if (Color.green.equals(color)) {
        greenCrayon.setSelected(true);
    } else if (Color.blue.equals(color)) {
        blueCrayon.setSelected(true);
    }
}
String getDisplayName()
Returns the display name of the chooser panel. 返回选择器面板的显示名称。The name is used on the tab for the chooser panel. 该名称在选择器面板的选项卡上使用。Here is the example getDisplayName method:下面是示例getDisplayName方法:
public String getDisplayName() {
    return "Crayons";
}
Icon getSmallDisplayIcon()
Returns a small icon to represent this chooser panel. 返回表示此选择器面板的小图标。This is currently unused. 这是当前未使用的。Future versions of the color chooser might use this icon or the large one to represent this chooser panel in the display. 颜色选择器的未来版本可能会使用此图标或较大的图标在显示器中表示此选择器面板。The example implementation of this method returns null.此方法的示例实现返回null
Icon getLargeDisplayIcon()
Returns a large icon to represent this chooser panel. 返回表示此选择器面板的大图标。This is currently unused. 这是当前未使用的。Future versions of the color chooser might use this icon or the small one to represent this chooser panel in the display. 颜色选择器的未来版本可能会使用此图标或小图标在显示器中表示此选择器面板。The example implementation of this method returns null.此方法的示例实现返回null

The Color Chooser API颜色选择器API

The following tables list the commonly used JColorChooser constructors and methods. 下表列出了常用的JColorChooser构造函数和方法。Other methods you might call are listed in the API tables in The JComponent Class. 您可能调用的其他方法在JComponent类的API表中列出。The API for using color choosers falls into these categories:使用颜色选择器的API分为以下几类:

Creating and Displaying the Color Chooser创建和显示颜色选择器
Method or Constructor方法或构造函数 Purpose目的
JColorChooser()
JColorChooser(Color)
JColorChooser(ColorSelectionModel)
Create a color chooser. 创建一个颜色选择器。The default constructor creates a color chooser with an initial color of Color.white. 默认构造函数创建初始颜色为Color.white的颜色选择器。Use the second constructor to specify a different initial color. 使用第二个构造函数指定不同的初始颜色。The ColorSelectionModel argument, when present, provides the color chooser with a color selection model.ColorSelectionModel参数(如果存在)为颜色选择器提供颜色选择模型。
Color showDialog(Component, String, Color) Create and show a color chooser in a modal dialog. 在模式对话框中创建并显示颜色选择器。The Component argument is the parent of the dialog, the String argument specifies the dialog title, and the Color argument specifies the chooser's initial color.Component参数是对话框的父级,String参数指定对话框标题,Color参数指定选择器的初始颜色。
JDialog createDialog(Component, String,
boolean, JColorChooser, ActionListener,
ActionListener)
Create a dialog for the specified color chooser. 为指定的颜色选择器创建对话框。As with showDialog, the Component argument is the parent of the dialog and the String argument specifies the dialog title. showDialog一样,Component参数是对话框的父级,String参数指定对话框标题。The other arguments are as follows: the boolean specifies whether the dialog is modal, the JColorChooser is the color chooser to display in the dialog, the first ActionListener is for the OK button, and the second is for the Cancel button.其他参数如下:boolean指定对话框是否为模态,JColorChooser是对话框中显示的颜色选择器,第一个ActionListener用于“确定”按钮,第二个用于“取消”按钮。
Customizing the Color Chooser's GUI自定义颜色选择器的GUI
Method方法 Purpose目的
void setPreviewPanel(JComponent)
JComponent getPreviewPanel()
Set or get the component used to preview the color selection. 设置或获取用于预览颜色选择的组件。To remove the preview panel, use new JPanel() as an argument. 要删除预览面板,请使用new JPanel()作为参数。To specify the default preview panel, use null.要指定默认预览面板,请使用null
void setChooserPanels(AbstractColorChooserPanel[])
AbstractColorChooserPanel[] getChooserPanels()
Set or get the chooser panels in the color chooser.在颜色选择器中设置或获取选择器面板。
void addChooserPanel(AbstractColorChooserPanel)
AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel)
Add a chooser panel to the color chooser or remove a chooser panel from it.将选择器面板添加到颜色选择器或从中删除选择器面板。
void setDragEnabled(boolean)
boolean getDragEnabled()
Set or get the dragEnabled property, which must be true to enable drag handling on this component. 设置或获取dragEnabled属性,该属性必须为true才能在此组件上启用拖动处理。The default value is false. 默认值为falseSee Drag and Drop and Data Transfer for more details.有关详细信息,请参阅拖放和数据传输
Setting or Getting the Current Color设置或获取当前颜色
Method方法 Purpose目的
void setColor(Color)
void setColor(int, int, int)
void setColor(int)
Color getColor()
Set or get the currently selected color. 设置或获取当前选定的颜色。The three integer version of the setColor method interprets the three integers together as an RGB color. setColor方法的三个整数版本将三个整数一起解释为RGB颜色。The single integer version of the setColor method divides the integer into four 8-bit bytes and interprets the integer as an RGB color as follows:setColor方法的单整数版本将整数分成四个8位字节,并将整数解释为RGB颜色,如下所示: How color chooser interprets an int as an RGB value.
void setSelectionModel(ColorSelectionModel)
ColorSelectionModel getSelectionModel()
Set or get the selection model for the color chooser. 设置或获取颜色选择器的选择模型。This object contains the current selection and fires change events to registered listeners whenever the selection changes.此对象包含当前选择,并在选择更改时向注册侦听器触发更改事件。

Examples that Use Color Choosers使用颜色选择器的示例

This table shows the examples that use JColorChooser and where those examples are described.下表显示了使用JColorChooser的示例以及这些示例的描述位置。

Example实例 Where Described描述位置 Notes备注
ColorChooserDemo This section本节 Uses a standard color chooser.使用标准颜色选择器。
ColorChooserDemo2 This section本节 Uses one customized color chooser and one standard color chooser in a dialog created with showDialog.在使用showDialog创建的对话框中使用一个自定义颜色选择器和一个标准颜色选择器。
TableDialogEditDemo How to Use Tables Shows how to use a color chooser as a custom cell editor in a table. 演示如何将颜色选择器用作表中的自定义单元格编辑器。The color chooser used by this example is created with createDialog.本示例使用的颜色选择器是使用createDialog创建的。
BasicDnD Introduction to DnDDnD简介 Uses a color chooser that is not in a dialog; demonstrates default drag-and-drop capabilities of Swing components, including color choosers.使用不在对话框中的颜色选择器;演示Swing组件的默认拖放功能,包括颜色选择器。

Previous page: How to Use the ButtonGroup Component
Next page: How to Use Combo Boxes